package com.google.code.gestion_de_conferences;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

 
public class AdduserActivity extends Activity {
	
	AABDatabaseManager db;
	Button adduser_btn;
	EditText reg_user_fullname,reg_user_phone,reg_user_username,reg_user_company;
	TextView reg_user_fullname_error,  reg_user_phone_error ,reg_user_username_error ,reg_user_company_error;
	int userPosition;
	
	
	/**
	 * @author Rayan Zahab
	 * @param Bundle
	 */
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Set View to adduser.xml
        setContentView(R.layout.adduser);
       
        db = new AABDatabaseManager(this);
        
        adduser_btn = (Button) findViewById(R.id.btn_adduser);
        reg_user_fullname = (EditText) findViewById(R.id.reg_user_fullname);
        reg_user_phone = (EditText) findViewById(R.id.reg_user_phone);
        reg_user_username = (EditText) findViewById(R.id.reg_user_username);
        reg_user_company = (EditText) findViewById(R.id.reg_user_company);
      
        reg_user_fullname_error = (TextView) findViewById(R.id.reg_user_fullname_error);
        reg_user_username_error = (TextView) findViewById(R.id.reg_user_username_error);
        reg_user_phone_error = (TextView) findViewById(R.id.reg_user_phone_error);
        
        //This is to get the position of the selected item from the usersList if we chose to edit the user
        Intent usersListIntent = getIntent(); 
       
        //-1 is the default value of the selectedUserId. This value will specify that no user was selected
        userPosition = usersListIntent.getIntExtra("selectedUserId", -1);    
       
        //we are editing a user
        if (userPosition != -1)
        {	
        	//change the activity title
        	setTitle("Edit User");
        	
        	//change button text
        	adduser_btn.setText("Edit User");
        	
        	//populate form with correct data if we are editing the user
        	populateForm(userPosition);
        	
        }
        
        adduser_btn.setOnClickListener
    	(
    		new View.OnClickListener()
	    	{
				@Override public void onClick(View v) {
			
				String name = reg_user_fullname.getText().toString();
		    	String phone = reg_user_phone.getText().toString();
		    	String username = reg_user_username.getText().toString();
		    	String company = reg_user_company.getText().toString();
		    	String is_admin = "0";
				register( userPosition, name,  username,  company,  phone, is_admin);
				
				}
			}
    	);     
    }

	 /**
	 * This function clears all errors in add user page
	 * @author Hyame Alameddine <halameddine@gmail.com> 
	 */
	private void clearErrors()
	{
		reg_user_fullname_error.setText( "");
        reg_user_phone_error.setText("");
        reg_user_username_error.setText("");
       
    }
	
	/**
	 * This function validates an email address format
	 * 
	 * @author Moustafa Chouraiki 
	 * 
	 * @param target mail to validate
	 * @return boolean
	 */
	 public final static boolean isValidEmail(CharSequence target)
	 {
	     if (target == null) 
	     {
	         return false;
	      }
	     else
	     {
	         return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
	     }
     }
	 
	/**
	 * This function validates the data sent on register and display the related error message
	 * 
	 * @author Rayan Zahab 
	 * 
	 * @param name
	 * @param username
	 * @param pass
	 * @param pass2
	 * @param phone
	 * 
	 * @return Boolean
	 */
	private Boolean validate(int userPosition, String name, String username, String company, String phone)
    {
        //first clear all error fields 
        clearErrors();
      
        Boolean error = false;
       
        if(name.length()<4)
        {
            error = true;
            reg_user_fullname_error.setText( "Name is minimum 4 digits!");
        }
      
        if(phone.length()!=8)
        {
            error = true;
            reg_user_phone_error.setText(  "Phone must be 8 digits!");
        }
        
        User u=new User();
		u.setEmail(username);
		
		//check if there is users that have the same email
        ArrayList<String> rowArray = db.getRowAsArrayByUser(u);
        
        //we are editing a user
        if (userPosition != -1 && rowArray.size()>0)
        {
        	  String editedUserId= userPosition+"";
        	  //check if the user having the same username is the edited user so we dont display the msg
        	  if(!editedUserId.equals(rowArray.get(0)))
        	  {
        		  error = true;
                  reg_user_username_error.setText("Username already exist!"); 
        		  
        	  }
        	  System.out.println(rowArray);
        }
        else
        {
        	if(rowArray.size()>0)
        	{
	            error = true;
	            reg_user_username_error.setText("Username already exist!");      
        	}
    	}
        if(username.length()<6)
        {
            error = true;
            reg_user_username_error.setText("User is minimum 6 digits!");
        }
        
        if(!isValidEmail(username.toString())) 
        {
                error = true;
                reg_user_username_error.setText("Email address is not Formatted !");
                
        }
        return error;
    }
	
/**
  * This function register a new Admin account into the DB
  * @author Rayan Zahab <differentruna@gmail.com> 
  * @author Hyame Alameddine <hyame.alameddine@gmail.com>
  * 
  * @param position This the position of the selected user
  * @param name
  * @param username
  * @param pass
  * @param pass2
  * @param phone
  * @param is_admin
  */
 private void register(int position,String name, String username,String company, String phone, String is_admin)
 {
    	Boolean error = validate(position, name,  username,  company,  phone);
    	
    	if(!error)
    	{
    		try
    		{   
    			User u  = new User();
    			
    			u.setFullName(name);
    			u.setEmail(username);
    			u.setIsAdmin("0");
    			u.setPhoneNumber(phone);
    			u.setCompany(company);
    			u.setPassword("");
    			
    			//Check if we have an item selected to edit or we are adding a new user
    			if (position != -1)
    			{
    				//set the user id to edit
    				u.setID(position);
    				
    				//update row
    				//db.updateRow (u);
    				
    				//success msg
    				Toast.makeText(this, "User successfully edited", Toast.LENGTH_LONG).show();
  		         
    			}				
        		else
        		{
        			// adding a new user
        			db.insertRow(u);
        			Toast.makeText(this, "User successfully added", Toast.LENGTH_LONG).show();	
        		}
    
    	    	Intent i = new Intent(getApplicationContext(), UsersListActivity.class);
    	        startActivity(i);
        	}
    		catch (Exception e)
        	{
        		Log.e("Update Error", e.toString());
        		e.printStackTrace();
        	}
    	}
    	
    }	
 	
 	/**
 	 * @author Hyame Alameddine <hyame.alameddine@gmail.com>
 	 * 
 	 * @param position
 	 */
 	private void populateForm (int position)
 	{	 		
 	 		
 		String fullName = db.getValueByParam(0,1,"User",position+"");
        String phone = db.getValueByParam(0,4,"User",position+"");
        String username = db.getValueByParam(0,2,"User",position+"");
        String company = db.getValueByParam(0,3,"User",position+"");
        
 		//populate the form
 		reg_user_fullname.setText(fullName); 
 		reg_user_username.setText(username);
 		reg_user_company.setText(company);
 		reg_user_phone.setText(phone);		
 		
 	}
 
	 /**
	   * This function create the menu options 
	   * @author Rayan Zahab <differentruna@gmail.com> 
	   * @param menu
	   */
	 @Override
	 public boolean onCreateOptionsMenu(Menu menu) {
	     MenuInflater inflater = getMenuInflater();
	     inflater.inflate(R.menu.menu, menu);              
	     return true;
	 }
	 
	 /**
	   * This function handles clicking any of the menu's items
	   * @author Rayan Zahab <differentruna@gmail.com> 
	   * @author Hyame Alameddine <hyame.alameddine@gmail.com>
	   * @param menu
	   */
	 @Override
	 public boolean onOptionsItemSelected(MenuItem item) 
	  {	  
		  Intent i;
		  
		  switch (item.getItemId()) 
		  {
	           
	          case R.id.users:     
	            	i = new Intent(getApplicationContext(), UsersListActivity.class);
	            	startActivity(i);
	                break;
	          case R.id.reservations:     
	            	i = new Intent(getApplicationContext(), ReservationsListActivity.class);
	            	startActivity(i);
	                break;
	          case R.id.conferences:     
	            	i = new Intent(getApplicationContext(), RoomsListActivity.class);
	            	startActivity(i);
	                break;
	          case R.id.edit_profile: 	        	  
	            	i = new Intent(getApplicationContext(), RegisterActivity.class);
	            	i.putExtra("editAdmin", 1);
	            	startActivity(i);
	                break;
	          case R.id.logout: 
	            	i = new Intent(getApplicationContext(), LoginActivity.class);
	            	startActivity(i);
	                break;
	          case R.id.help:     
	                AlertDialog alertDialog = new AlertDialog.Builder(this).create();
	                alertDialog.setTitle("Help!");
	                alertDialog.setMessage("Gestion de conference is an application helps you manage reservations, add rooms ,add users and reserve rooms to organize conferences !");
	                alertDialog.setIcon(R.drawable.icon);
	                alertDialog.show();
	                break;
	          case R.id.developers: 
	            	Toast.makeText(this, "Rayan,Hyam,Mostafa!", Toast.LENGTH_LONG).show();
	                break;
	            
	       }
	        return true;
	    }
}
